"use strict";

const { Controller } = require("egg");

class BrokerController extends Controller {
  // 获取资讯数据
  async getBroker() {
    const { ctx } = this;
    const { type, value } = ctx.query;
    const list = await this.app.mysql.select("broker");
    ctx.body = {
      code: 200,
      list: list
        .filter((v) => {
          if (type === "全部") {
            return true;
          }
          return v.state === type;
        })
        .filter((v) => {
          if (value == "") {
            return true;
          }
          return v.name.includes(value);
        }),
    };
  }


  // 新增资讯
  async addBroker() {
    const { ctx } = this;
    const { tel, name,company,newSum,twoSum,rentalSum} = ctx.request.body;
    const res = await this.app.mysql.insert("broker", {
      tel, name,company,newSum,twoSum,rentalSum
    });
    if (res.affectedRows === 1) {
      ctx.body = {
        code: 200,
      };
    } else {
      ctx.body = {
        code: 300,
      };
    }
  }
  // 编辑资讯
  async editBroker() {
    const { ctx } = this;
    const { tel, name,company,newSum,twoSum,rentalSum, key } = ctx.request.body;
    const res = await this.app.mysql.update(
      "broker",
      {tel, name,company,newSum,twoSum,rentalSum },
      { where: { key } }
    );
    if (res.affectedRows === 1) {
      ctx.body = {
        code: 200,
      };
    } else {
      ctx.body = {
        code: 300,
      };
    }
  }

  //   禁用经纪人
  async disableList() {
    const { ctx } = this;
    const { state, key } = ctx.request.body;
    if (state == "在职") {
      const post = await this.app.mysql.update(
        "broker",
        { state: "离职" },
        { where: { key } }
      );
      if (post.affectedRows === 1) {
        ctx.body = {
          code: 200,
          msg: "禁用成功",
        };
      } else {
        ctx.body = {
          code: 300,
          msg: "禁用失败",
        };
      }
    } else {
      const post = await this.app.mysql.update(
        "broker",
        { state: "在职" },
        { where: { key } }
      );
      if (post.affectedRows === 1) {
        ctx.body = {
          code: 200,
          msg: "启用成功",
        };
      } else {
        ctx.body = {
          code: 300,
          msg: "启用失败",
        };
      }
    }
  }
}

module.exports = BrokerController;
